import 'package:flutter/services.dart';
import 'package:flutter_common_ui/src/common_ui_config.dart';

class AssetsUtils {
  const AssetsUtils._();

  static final Map<String, bool> _assetCache = {};

  // 检查资源文件是否存在，优先从缓存中获取
  static Future<bool> assetExistsAsync(String path) async {
    if (_assetCache.containsKey(path)) {
      return _assetCache[path]!;
    }

    // 如果不在缓存中，进行异步检查并缓存结果
    Future<bool> checkAssetExists() async {
      try {
        await rootBundle.load(path);
        _assetCache[path] = true;
        return true;
      } catch (_) {
        _assetCache[path] = false;
        return false;
      }
    }

    // 使用 Future.sync 来同步执行异步操作
    return Future.sync(() => checkAssetExists()).then((value) => value);
  }

  // 检查资源文件是否存在
  static bool assetExists(String path) {
    return CommonUiConfig.getAssetsMap().contains(path);
  }

  //转换成夜间模式的资源路径
  static String _getDarkAssetPath(String path) {
    final newPath = path.replaceAll('assets/svg/', 'assets/svg/dark/').replaceAll('assets/img/', 'assets/img/dark/');
    if (assetExists(newPath)) {
      return newPath;
    }
    return path;
  }

  //转换成渠道包的资源路径
  static String _getAppTypeAssetPath(String path) {
    final newPath = path.replaceAll('assets/svg/', 'assets/svg/${CommonUiConfig.getAppTypeName()}/').replaceAll('assets/img/', 'assets/img/${CommonUiConfig.getAppTypeName()}/');
    if (assetExists(newPath)) {
      return newPath;
    }
    return path;
  }

  //转换成渠道包的资源路径
  static String _getAppTypeAndDarkAssetPath(String path) {
    final newPath = path.replaceAll('assets/svg/', 'assets/svg/dark/${CommonUiConfig.getAppTypeName()}/').replaceAll('assets/img/', 'assets/img/dark/${CommonUiConfig.getAppTypeName()}/');
    if (assetExists(newPath)) {
      return newPath;
    }
    return path;
  }

  //转换路径
  static String convertPath(String path) {
    final isDarkMode = CommonUiConfig.isDark();
    if (isDarkMode) {
      //优先判断渠道包下面是否有图标
      final appTypePath = _getAppTypeAssetPath(path);
      if (appTypePath == path) {
        //没有渠道图标，那么取夜间模式的图标
        return _getDarkAssetPath(path);
      } else {
        //有渠道图标，那么判断对应夜间模式的渠道下是否有图标
        final appTypeAndDarkPath = _getAppTypeAndDarkAssetPath(path);
        if (appTypeAndDarkPath == path) {
          //没有夜间模式渠道图标,那么直接返回非夜间模式渠道图标
          return appTypePath;
        } else {
          return appTypeAndDarkPath;
        }
      }
    } else {
      return _getAppTypeAssetPath(path);
    }
  }
}
